package com.example.demo.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.shiro.SecurityUtils; 
import org.apache.shiro.subject.Subject; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
import com.example.demo.common.JwtTokenUtils;
import com.example.demo.constants.ResultEnity; 
import com.example.demo.constants.pojo.UserInfo;
import com.example.demo.sao.ICacheSao;
import com.example.demo.service.IUserService;
import com.example.demo.shiro.ShiroSimpleJwtToken;

import io.swagger.annotations.Api; 
import lombok.extern.log4j.Log4j2;

@Log4j2
@RestController
@RequestMapping("/security")
@Api(tags = "登陆退出接口文档")
public class LoginoutController {

	@Value("${demo-settings.ServerHost}")
	private String serverHost;
	
	@Value("${demo-settings.RememberMe}")
	private boolean rememberMe=false;
	
	@Value("${demo-settings.SessionTimeout}")
	private long sessionTimeout;

	/**
	 * 缓存服务
	 */
	@Autowired
	ICacheSao cacheSao;

	
	/**
	 * 用户服务
	 */
	@Autowired
	IUserService userService; 
	
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ResultEnity<UserInfo> Login(@RequestBody UserInfo userInfo){	//@ApiParam(name = "userName", value = "登陆帐号", required = true) String userName,@ApiParam(name = "password", value = "登陆密码", required = true) String password	
		String message="";
		
		//UserInfo userInfo=new UserInfo();	
		String userName=userInfo.getUserName();
		String password=userInfo.getPassword();
		
		userInfo= userService.QueryUserInfoByUserName(userName);
		
		System.out.println(userInfo);
		
		if(userInfo!=null && userInfo.getPassword().equals(password)) {
            
			Subject subject=SecurityUtils.getSubject();
            
		    Date loginDateTime=new Date();
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	        System.out.println("用户 "+userInfo.getUserName()+ " 于 " + df.format(loginDateTime)+" 登陆系统"); 
			
	        Calendar calendar =Calendar.getInstance();  
	        calendar.setTime(loginDateTime);
	        calendar.add(Calendar.MILLISECOND, (int)sessionTimeout);
	        Date loginExpireTime=calendar.getTime();	
	        System.out.println("用户 "+userInfo.getUserName()+ " 于 " + df.format(loginExpireTime)+" 登陆超时"); 

			ShiroSimpleJwtToken token=new ShiroSimpleJwtToken(userInfo.getUserName(), userInfo.getPassword(), loginExpireTime, rememberMe);
			
//			token.setHost(serverHost);
			token.setUserId(userInfo.getUserId());	
			
			subject.login(token);   
            
            String sessionId=subject.getSession().getId().toString();   
            userInfo.setSessionId(sessionId);
            System.out.println(sessionId);

            String tokenString=JwtTokenUtils.deserializeString(token);
            log.info(tokenString);
            
            try {            	             
            	cacheSao.Set(userInfo.getUserId(), userInfo.getUserName());
            } 
            catch (Exception ex) {
				// TODO: handle exception
            	log.info("登陆成功，但设置缓存失败:"+ex.getMessage());
			}
            
            userInfo.setToken(tokenString);
            
			message="登陆成功";
			log.info(userInfo.getUserName() +" 登陆成功");
			
		}
		else {
			
			System.out.println("用户名或密码不正确");
			
			return ResultEnity.Error("用户名或密码不正确", null);
			
		}
		
		
		return ResultEnity.Success(message, userInfo);		
	}
	
	@RequestMapping("/logout")
	public ResultEnity<String> Logout() {
		Subject subject = SecurityUtils.getSubject();
		String userName = (String)subject.getPrincipal();   
	    
		UserInfo userInfo = userService.QueryUserInfoByUserName(userName);
	    cacheSao.Delete(userInfo.getUserId());
	    subject.logout();
	    
	    return ResultEnity.Success("操作成功", "用户  "+userName+" 已退出");
	}
	
}
